<template>
	<view>
		<view class="upload">
			<view class="upload-image">
				<!-- 图片列表 -->
				<view class="upload-image-list" v-for="(item, index) in showImgs" :key="index" @tap="imageTap(index)">
					<image class="upload-image-item" :src="item" :mode="mode"></image>
				</view>
				<!-- 添加图片 -->
				<view class="upload-add-img" @click="addImage" v-show="isAddImg">
					<view class="iconfont upload-add-icon">
						&#xe646;
					</view>
				</view>
			</view>
		</view>
		<view class="upload-convas" :style="{width:cWidth+'px',height:cHeight+'px',}">
			<canvas id="myCanvas" canvas-id="myCanvas" :style="{width:cWidth+'px',height:cHeight+'px',}" />
		</view>
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	// #ifdef APP-PLUS
	import amap from '../../common/amap-wx.js';
	// #endif
	export default {
		name: 'upload-image',
		props: {
			Token: { // 上传图片类型
				type: String,
				default: ''
			},
			UserCode: { // 上传图片类型
				type: String,
				default: ''
			},
			Kind: { // 上传图片类型
				type: String,
				default: 'Goods'
			},
			mode: { // 图片裁剪,缩放模式
				type: String,
				default: 'scaleToFill'
			},
			imageCount: { // 上传图片数量
				type: [Number, String],
				default: 0
			},
			showImageSrc: {
				type: Array,
				default: () => {
					return []
				}
			},
		},
		data() {
			return {
				amapPlugin: null,
				key: '99884d8f70a18bf10e7d16cfba0c74a5',  //高德key
				Address: '',
				cWidth: '',
				cHeight: '',
				ql: 1,
				showImgs: [],
				isAddImg: true,
			};
		},
		created() {
			this.showImgs = this.showImageSrc || [];
		},
		mounted() {
			// 高德地图
			// #ifdef APP-PLUS
			this.amapPlugin = new amap.AMapWX({  
				key: this.key  
			}); 
			// #endif
		},
		destroyed() {

		},
		watch: {
			showImageSrc(n, o) {
				this.showImgs = n || [];
				if (this.showImgs.length >= this.imageCount) {
					this.isAddImg = false;
				} else {
					this.isAddImg = true;
				}
			}
		},
		methods: {
			addImage() {
				let that = this;
				// #ifdef APP-PLUS
				this.getRegeo();
				// uni.getLocation({
				//     type: 'gcj02',
				// 	geocode: true,
				//     success: function (res) {
				// 		that.Address = '' + res.address.city + res.address.district + res.address.street + res.address.streetNum
				//     }
				// });
				// #endif
				let imageLength = that.showImgs.length;

				if (imageLength >= that.imageCount) {
					uni.showToast({
						title: `最多选取${that.imageCount}张图片`,
						icon: 'none',
						duration: 1500
					});
					return;
				}
				
				var p = that.getImageBase64();
				p.then(imageBase64 => {
					that.uploadServerImage(imageBase64);
				})
			},
			async uploadServerImage(imageBase64) {
				let that = this;
				let requestData = {
					MethodCode: "App_SaveImage",
					Token: that.Token,
					FileInfo: imageBase64,
					Info: {
						"UserCode": that.UserCode,
						"Kind": that.Kind,    // 类别（Company,Goods）
						"Info": '',
					}
				};
				// console.log(requestData);
				await that.$request.globalRequest('', 'POST', requestData, 'Image', 0).then(res => {
					console.log(res.data);
					if (that.$common.responseBuilder(res.data).Status !== '0' && that.$common.responseBuilder(res.data).Data.length !== 0) {
						let data = that.$common.responseBuilder(res.data).Data[0];
						console.log(data);
						that.showImgs.push(data.FileNameFull)
						var returnData = {
							showImageSrc: that.showImgs
						}
						uni.hideLoading();
						that.$emit('change', returnData);
					}
				}).catch(res => {
					uni.hideLoading();
					uni.showToast({
						title: `上传失败，请重新上传`,
						icon: 'none',
						duration: 1500
					});
					console.log(res);
				})
			},
			imageTap(index) {
				let that = this;
				uni.showActionSheet({
					itemList: ['全屏预览大图', '删除（不可撤销）'],
					success: res => {
						if (res.tapIndex) { // 删除
							that.imageDel(index)
						} else { // 预览
							that.previewImage(index)
						}
					}
				})
			},
			imageDel(index) {
				let that = this;
				that.showImgs.splice(index, 1)
				var returnData = {
					showImageSrc: that.showImgs
				}
				that.$emit('change', returnData);
			},
			previewImage(index) {
				uni.previewImage({
					current: this.showImgs[index],
					urls: this.showImgs
				})
			},
			getOriginalImageBase64() {
				// 获取未压缩图片
				let that = this;
				var pmise = new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], //从相册选择
						success: function(chooseImageRes) {
							const tempFilePaths = chooseImageRes.tempFilePaths;
							// #ifdef MP-WEIXIN
							let base64 = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(tempFilePaths[0], "base64")
							resolve(base64);
							//#endif
							//#ifdef APP-PLUS													

							plus.io.resolveLocalFileSystemURL(tempFilePaths[0], function(entry) {
								entry.file(function(file) {
									let fileReader = new plus.io.FileReader();
									fileReader.readAsDataURL(file);
									fileReader.onloadend = function(evt) {
										if (evt.target.readyState == 2) {
											resolve(evt.target.result);

										}
									}
								});
							}, function(e) {});
							//#endif
							//#ifdef H5
							pathToBase64(tempFilePaths[0])
								.then(base64 => {
									resolve(base64);
								})
								.catch(error => {
									console.error(error)
								})
							// resolve(tempFilePaths[0]);	
							//#endif
						}
					});
				});
				return pmise;
			},
			getImageBase64() {
				// 获取压缩图片
				let that = this;
				var pmise = new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['camera'], //从相册选择
						success: function(chooseImageRes) {
							// console.log(chooseImageRes.tempFiles[0].size / 1024)
							// let imageSize = chooseImageRes.tempFiles[0].size / 1024;
							// if(imageSize > 1024) {
							// 	uni.showToast({
							// 		title: `单张图片大小不能超过1MB`,
							// 		icon: 'none',
							// 		duration: 1500
							// 	});
							// 	return;
							// }
							uni.showLoading({
								title: '上传中'
							});
							const tempFilePaths = chooseImageRes.tempFilePaths;
							// //#ifdef H5
							// 	pathToBase64(tempFilePaths[0])  
							// 	  .then(base64 => {  
							// 		resolve(base64);	
							// 	  })  
							// 	  .catch(error => {  
							// 		console.error(error)  
							// 	  })
							// 	// resolve(tempFilePaths[0]);	
							// //#endif
							uni.getImageInfo({
								src: tempFilePaths[0],
								success: (res) => {
									let pixels = 640000; // 最大分辨率，宽 * 高 的值
									let quality = 0.8; // 压缩质量
									// 图片原始尺寸
									var originWidth = res.width;
									var originHeight = res.height;
									// // 最大尺寸限制
									// var maxWidth = 400, maxHeight = 400;
									// // 目标尺寸
									// var targetWidth = originWidth, targetHeight = originHeight;
									// // 图片尺寸超过400x400的限制
									// if (originWidth > maxWidth || originHeight > maxHeight) {
									// 	if (originWidth / originHeight > maxWidth / maxHeight) {
									// 		// 更宽，按照宽度限定尺寸
									// 		targetWidth = maxWidth;
									// 		targetHeight = Math.round(maxWidth * (originHeight / originWidth));
									// 	} else {
									// 		targetHeight = maxHeight;
									// 		targetWidth = Math.round(maxHeight * (originWidth / originHeight));
									// 	}
									// }
									// 目标尺寸
									let target = that.calcImageSize(res, pixels);
									let targetWidth = target.imgW;
									let targetHeight = target.imgH;
									// canvas对图片进行缩放
									that.cWidth = targetWidth;
									that.cHeight = targetHeight;

									//#ifdef H5
									let img = new Image()
									img.src = res.path
									img.onload = () => {
										const canvas = document.createElement('canvas')
										const context = canvas.getContext('2d')
										canvas.width = targetWidth
										canvas.height = targetHeight
										let drawW = targetWidth,
											drawH = targetHeight

										context.drawImage(img, 0, 0, drawW, drawH)

										let base64 = canvas.toDataURL(`image/jpg`, quality)

										resolve(base64)
									}
									//#endif

									// #ifndef H5
									const ctx = uni.createCanvasContext('myCanvas', that);
									// 设置地址和时间
									const fz30 = uni.upx2px(50)
									let locationY = that.cHeight - 80;
									let locationX = 20;
									let dateY = that.cHeight - 40;
									let location = that.Address;
									let date = that.$common.dateFormat('YYYY-mm-dd HH:MM', new Date());
									
									ctx.drawImage(res.path, 0, 0, that.cWidth, that.cHeight);
									ctx.setFillStyle('#FFFFFF')
									ctx.setFontSize(fz30)
									ctx.fillText(location, locationX, locationY)
									ctx.fillText(date, locationX, dateY)

									setTimeout(() => {
										ctx.draw(false, () => {
											setTimeout(() => {
												uni.canvasToTempFilePath({
													width: Number(that.cWidth),
													height: Number(that.cHeight),
													destWidth: Number(that.cWidth),
													destHeight: Number(that.cHeight),
													canvasId: 'myCanvas',
													fileType: 'jpg',
													quality: Number(that.ql),
													success: function(res) {
														// #ifdef MP-WEIXIN
														let base64 = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(res.tempFilePath,
															"base64")
														resolve(base64);
														//#endif
														//#ifdef APP-PLUS													

														plus.io.resolveLocalFileSystemURL(res.tempFilePath, function(entry) {
															entry.file(function(file) {
																let fileReader = new plus.io.FileReader();
																fileReader.readAsDataURL(file);
																fileReader.onloadend = function(evt) {
																	if (evt.target.readyState == 2) {
																		resolve(evt.target.result);

																	}
																}
															});
														}, function(e) {});
														//#endif
														//#ifdef H5
														pathToBase64(tempFilePaths[0])
															.then(base64 => {
																resolve(base64);
															})
															.catch(error => {
																console.error(error)
															})
														// resolve(res.tempFilePath);
														//#endif
													},
													complete: function(res) {}
												}, that)
											}, 50)
										})
									}, 300)
									// #endif
								}
							})
						}
					});
				});
				return pmise;

			},
			calcImageSize(res, pixels) {
				let imgW, imgH
				imgW = res.width
				imgH = res.height

				let ratio
				if ((ratio = imgW * imgH / pixels) > 1) {
					ratio = Math.sqrt(ratio)
					imgW = parseInt(imgW / ratio)
					imgH = parseInt(imgH / ratio)
				} else {
					ratio = 1
				}
				return {
					imgW,
					imgH
				}
			},
			getRegeo() {
				// 获取当前地址
				// uni.showLoading({  
				// 	title: '获取信息中'  
				// });  
				this.amapPlugin.getRegeo({  
					success: (data) => {  
						// console.log(data)  
						this.Address = data[0].name;
						// this.longitude = data[0].longitude;
						// this.latitude = data[0].latitude;
						// this.city = data[0].regeocodeData.addressComponent.city;
						// this.district = data[0].regeocodeData.addressComponent.district;
						uni.hideLoading();  
					},
					fail: (res) => {
						console.log(res)
					}
				});  
			},
		}
	}
</script>

<style>
	.upload-image {
		display: flex;
		flex-wrap: wrap;
		padding: 8rpx 32rpx 0 16rpx;
	}

	.upload-image-list {
		/* padding: 0 32rpx 0 0; */
		float: left;
	}

	.upload-image-item {
		width: 200rpx;
		height: 200rpx;
		margin-left: 16rpx;
	}

	.upload-add-img {
		width: 200rpx;
		height: 200rpx;
		background: rgba(238, 238, 238, 1);
		margin-left: 16rpx;
		/* margin: 0 0 32rpx 32rpx; */
	}

	.upload-add-icon {
		font-size: 56rpx;
		color: #D2D2D2;
		align-items: center;
		text-align: center;
		line-height: inherit;
		line-height: 200rpx;
	}

	.upload-convas {
		/* 将canvas移到界面外实现隐藏效果 */
		position: fixed;
		top: -9999999999999rpx;
		visibility: hidden;
		overflow: hidden;
		/* position: fixed;  
		width: 800rpx;  
		height: 800px;  
		left: -800px;  
		top: 0; */
		/* position: absolute;
		left: 20000rpx;
		visibility: hidden;
		height: 0;
		overflow: hidden; */
	}
</style>
